﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;
using VisualStock.Infrastructure;
using VisualStock.Infrastructure.Interfaces;
using VisualStock.Infrastructure.Models;

namespace VisualStock.Modules.StockSymbols.Services
{
    public class ComparingSymbolService : IComparingSymbolService
    {
        private ObservableSymbolCollection _availableSymbols = new ObservableSymbolCollection();

        private IEventAggregator EventAggregator { get; set; }

        public ComparingSymbolService(IEventAggregator eventAggregator)
        {
            this.EventAggregator = eventAggregator;
            // Update the avaiable symbol list when new data was obtained
            this.EventAggregator.GetEvent<NewHistoricalDataObtainedEvent>().Subscribe(UpdateAvaiableSymbols, ThreadOption.UIThread);
        }

        public void UpdateAvaiableSymbols(string newObtainedSymbol)
        {
            foreach (ObservableSymbolItem item in _availableSymbols)
            {
                if (item.Symbol == newObtainedSymbol)
                {
                    return;
                }
            }

            // Add the new obtained symbol if it is not in the _comparingSymbolList
            _availableSymbols.Add(new ObservableSymbolItem
            {
                Symbol = newObtainedSymbol,
                DataStatus = SymbolDataStatus.Cached
            });

            List<string> newItems = new List<string>() { newObtainedSymbol };
            this.AvailableSymbolChanged(_availableSymbols, new AvailableSymbolChangedEventArgs { NewItems = newItems });
        }

        #region IComparingSymbolService Members

        public event EventHandler<AvailableSymbolChangedEventArgs> AvailableSymbolChanged;

        public ObservableSymbolCollection GetAvailableSymbols()
        {
            return _availableSymbols;
        }

        public void RemoveSymbols(List<string> targetSymbols)
        {
            List<string> removedList = new List<string>();
            foreach (string target in targetSymbols)
            {
                var targetItem = (from item in _availableSymbols
                                  where item.Symbol == target
                                  select item).Single<ObservableSymbolItem>();
                if (targetItem != null)
                {
                    _availableSymbols.Remove(targetItem);
                    removedList.Add(targetItem.Symbol);
                }
            }
            this.AvailableSymbolChanged(_availableSymbols, new AvailableSymbolChangedEventArgs { OldItems = removedList });
            this.EventAggregator.GetEvent<SymbolRemovedEvent>().Publish(removedList);
        }

        #endregion
    }
}
